from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
import uuid
# from execute.models import *
# from Common.Common_task import *
# from .models import *
from Common.Common_api2 import testcasedata_view
from Common.Common_task import *
from Common.Common_webservice import xmlDataBuild
from Common.requests import *
# from Common.Common_api import *
from backend.common.assertapi import *
from django.views.generic import View
from Common.Common_statistics import *
from Common.Common_authentication import *
from Common.Common_api2 import *
from rest_framework.views import APIView
from Common.Common_fields_check import *
from backend.common.common_pici import *
from backend.common.common_db import *
from Common.Common_msg import *
# from backend.enn.en import *
from backend.common.common_function import *
from Common.Common_webservice import *
import xmltodict
import numpy as np

from backend.serializers import Sys_CaseParamSerializer

"""
        新思路前提:  http://127.0.0.1:8000/execute/autotestapi/
        1.已知项目id=1；
        2.选择的环境已确定;
        3.接口执行表中已知被勾选接口id为1，2 ；interface_action=[1,2]
        4.已知常规校验执行=0； 业务执行=1 （常规校验时，只支持一个接口对应一条疏通测试案例）


"""

interface_succcess_list = []
interface_fail_list = []
teascase_pass = 0
teascase_fail = 0

regular_check_seccess_data = []


# 既有常规校验又有逻辑校验接口；选择的是逻辑。默认常规校验的自动执行失败；
# [1,2,3,4]


# class getResult(APIView):
class getResult():
    def get(self, request, *args, **kwargs):

        # type 为0时为流程测试
        # content = {
        #     "progect_id": project_id,
        #     "environment_id": environment_id,
        #     "run_seq_new_mock": run_seq_new_mock,
        #     "run_seq_new_ids": run_seq_new_ids,
        #     "execute": case_type_code_id,
        #     'type': "0",
        #     "run_ac_new:"run_ac_new"

        # }
        # msg = getResult.get(request, content)


        progect_id = request['progect_id']
        environment_id = request['environment_id']
        # execute = request['execute']  # 执行条件
        type = request['type']
        print(type)
        # print("execute")
        # print(execute)

        if type == '0':  # type 为0时为流程测试
            run_seq_new_mock = request['run_seq_new_mock'] #执行顺序
            interface_action = request['run_seq_new_ids']
            print(run_seq_new_mock)
            print(interface_action)

            print("ABCDE")
            # execute = request['execute']  # 执行条件
            execute = request['execute']  # 执行条件

            run_ac_new=request['run_ac_new']
            print(request['run_ac_new'])  # eg: {300: 82, 359: 108, 303: 86, 341: 103, 346: 113, 347: 121}
            """
            由于数据库默认给的是疏通测试
            所以如果是流程测试需要将执行条件更换
            暂时设定为1101 由common_function传参
            
            """

            # print(execute)


        else:  # type 为1时为接口测试
            interface_action = request['interface_action']  # 原执行列表
            interface_mock = request['interface_mock']  # mock执行接口列表

            execute = request['execute']  # 执行条件
            print(interface_action)
            print(interface_mock)

        #     直接调MOCK待补充补充

        global interface_fail_list
        interface_fail_list.clear()
        interface_succcess_list.clear()



        # 创建批次号
        interface_pici = InterfacePici().Interface_Pici()
        interface_pici = int(interface_pici)
        print(interface_pici)
        print(execute)

        if execute == "0":  # 疏通测试
            if type == "0":  # type0   流程测试
                """
                此处不再走；因为流程测试不再传excute
                
                """
                pass
                # statistics_interface_result = getResult().autotestapis_views(environment_id, interface_action,progect_id, interface_pici, execute, type,run_seq_new_mock)

            else:
                statistics_interface_result = getResult().autotestapis_views(environment_id, interface_action,
                                                                             progect_id, interface_pici, execute, type)



        elif execute == "1"  :  # 逻辑校验测试
            if type == "0":

                """
                此处不再走；因为流程测试不再传excute

                """
                pass

                # statistics_interface_result = getResult().autotestapis_views(environment_id, interface_action,progect_id, interface_pici, execute, type,run_seq_new_mock)
            else:
                statistics_interface_result = getResult().autotestapis_views(environment_id, interface_action,
                                                                             progect_id, interface_pici, execute, type)

            global regular_check_seccess_data

            # print("regular_check_seccess_data:%s"%regular_check_seccess_data)
            return JsonResponse({"code": "999999", "msg": "业务逻辑执行成功"})




        elif execute == "2":  # 常规校验测试
            statistics_interface_result = getResult().autotestapis_views(environment_id, interface_action, progect_id,
                                                                         interface_pici, execute, type)

            # print(statistics_interface_result)  #统计本次执行接口个数+成功接口个数+失败接口个数+批次号+本批次执行列表+成功列表+失败列表+接口最终执行结果  (1, 1, 0, 20210120571, ['237'], ['237'], [], '成功')
            # print("跑完疏通后的返回值，应该再取接口信息维度") #(2, 1, 1, 20210125980, ['237', '285'], ['285'], ['237'], '失败')

            if len(statistics_interface_result[5]) == 0:  # 疏通全部失败，没有成功的接口直接存储结果

                # 删除已生成记录
                runMessage().delMsg()

                # 新增新记录
                del_statistics_interface_action_detail(statistics_interface_result[3])  # 删除用例详情表中记录，不占数据库
                project_name = Project.getProjectName(progect_id)
                environment_name = Environment.getEnvironmentName(environment_id)[0]['env_name']

                msg = mas_view(project_name, environment_name,
                               statistics_interface_result[3],
                               statistics_interface_result[0],
                               statistics_interface_result[1],
                               statistics_interface_result[2])

                json_msg = json.dumps(msg, ensure_ascii=False)

                """此处加数据到表用于以后查询"""
                model = "执行接口"
                """增加"""
                runMessage.addMsg(json_msg, model)


            else:
                # print("疏通执行成功，删除用例汇总表中及用例详情表中记录")
                del_statistics_interface_action_detail(statistics_interface_result[3])  # 删除用例详情表中记录
                del_statistics_interface_action(statistics_interface_result[3],
                                                statistics_interface_result[5])  # 删除执行成功列表的用例汇总表中记录

                # 用例统计维度（疏通成功/失败记录）
                # 接口成功的测试案例
                regular_check_seccess_data = regular_check_seccess_screen(regular_check_seccess_data,
                                                                          statistics_interface_result[5])

                # 接收常规校验执行结果
                interface_res_result_list_totle = Regular_Check(statistics_interface_result[5],
                                                                regular_check_seccess_data, interface_pici)

                # 判断执行的接口与维护表毫无关系的情况
                common_table_check1 = common_table_check(interface_res_result_list_totle, interface_pici)
                interface_message = statistics_interface_action_rewrite(common_table_check1,
                                                                        statistics_interface_result)

                # 删除已生成记录
                runMessage().delMsg()

                # 查询项目名称 + 环境名称
                project_name = Project.getProjectName(progect_id)
                environment_name = Environment.getEnvironmentName(environment_id)[0]['env_name']

                msg = mas_view(project_name, environment_name,
                               interface_message['pici'],
                               interface_message['interface_action_count'],
                               interface_message['success_count'],
                               interface_message['fail_count'])

                json_msg = json.dumps(msg, ensure_ascii=False)

                """此处加数据到表用于以后查询"""
                model = "执行接口"
                """增加"""
                runMessage.addMsg(json_msg, model)

        elif execute =='1101' :
            print("ASDFG1")#{341: 114, 342: 111} 执行接口-用例对应字典
            print(run_ac_new )

            statistics_interface_result = getResult().autotestapis_views(environment_id, interface_action,progect_id, interface_pici, execute, type,run_seq_new_mock,run_ac_new)




        else:
            print("quxiao------------")
            pass


        # 批量执行多接口

    def autotestapis_views(self, *args, **kwargs):
        print(args) #eg ('9', ['341', '342'], '7', 202104131534321, 1101, '0', ['341|0', '342|0'])


        environment_id = args[0]
        interface_action = args[1]
        progect_id = args[2]
        interface_pici = args[3]
        execute = args[4]  # 执行条件
        type = args[5]


        # 1.获取测试环境信息
        self.environment_data = data_environment_view(environment_id)
        print("环境信息：%s" % (self.environment_data))
        """
        
        {'environment_id': '9', 'environment_address': 'http://192.168.16.51:30911/', 'environment_name': '广州政采贷-webservice'}
        """


        # 2.已知勾选需要执行的接口id
        # print(type)



        if type == "0":  # 流程测试
            interface_action_part = []  # 正常接口|0
            interface_mock = []  # MOCK接口|1
            for i in args[6]:
                print(i)
                list1 = i.split("|")
                if list1[1] == "0":
                    #     正常走执行
                    interface_action_part.append(list1[0])
                elif list1[1] == "1":
                    #     走mock
                    interface_mock.append(list1[0])
                else:
                    print("输入接口类型有误，暂只支持正常执行或mock")
            print(interface_action_part)
            print(interface_mock)
            print("马嘉璐注意啦2222222222！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！")

            #  正常接口|0 调取
            for self.interfaces_id in interface_action_part:
                global teascase_pass, teascase_fail
                teascase_pass = 0
                teascase_fail = 0

                # 3.取接口信息拼接
                self.test_interfaces_datas = data_interface_view(self.interfaces_id)
                print(self.test_interfaces_datas)
                print("取接口信息拼接")

                # 4.调用测试案例视图函数  --用例
                self.autotestapi_views(self.interfaces_id, self.test_interfaces_datas, self.environment_data,
                                       interface_pici, execute, progect_id,args[7])  # 新增1


            # mock调取 暂时没写，视为失败，统计失败个数
            for interface_mock_id in interface_mock:
                # MOCK接口|调接口pass,暂未编写mock，统计为失败
                teascase_fail += 1
                interface_fail_list.append(interface_mock_id)



        else:  # type = 1接口测试
            for self.interfaces_id in interface_action:
                # global teascase_pass, teascase_fail
                # teascase_pass = 0
                # teascase_fail = 0

                # 3.取接口信息拼接
                self.test_interfaces_datas = data_interface_view(self.interfaces_id)
                print(self.test_interfaces_datas)
                print("取接口信息拼接")

                # 4.调用测试案例视图函数
                self.autotestapi_views(self.interfaces_id, self.test_interfaces_datas, self.environment_data,
                                       interface_pici, execute, progect_id)  # 新增1

            #    6-1 接口统计
        self.statistics_interface_result = statistics_interface_action(interface_pici, environment_id, interface_action,
                                                                       interface_succcess_list, interface_fail_list,
                                                                       progect_id, execute)

        project_name = Project.getProjectName(progect_id)

        msg = mas_view(project_name, self.environment_data['environment_name'],
                       self.statistics_interface_result[3], self.statistics_interface_result[0],
                       self.statistics_interface_result[1],
                       self.statistics_interface_result[2])

        json_msg = json.dumps(msg, ensure_ascii=False)

        """此处加数据到表用于以后查询"""
        model = "执行接口"
        """增加"""
        runMessage.addMsg(json_msg, model)

        return self.statistics_interface_result

    #     测试案例视图
    def autotestapi_views(self, *args, **kwargs):
        print("用例维度的args,是否取到webservice")
        print("args")
        print(args)
        print("self")
        print(args[0])



        print(self)
        # print(self.interface_id)


        """
        args
        
        args = {tuple: 6} ('343', ({'interface_data': {'interfaces_id': '343', 'interfaces_name': 'C1221', 'api': 'credit-data-biz/services/RFPServerForBankService?wsdl', 'method': 'POST', 'param_data': '{"SOURCE": "", "SOURCE_CODE": "", "FIN_CODE": "", "SUPPLIER_NAME": "", "SUPPLI
         0 = {str} '343'
         1 = {tuple: 2} ({'interface_data': {'interfaces_id': '343', 'interfaces_name': 'C1221', 'api': 'credit-data-biz/services/RFPServerForBankService?wsdl', 'method': 'POST', 'param_data': '{"SOURCE": "", "SOURCE_CODE": "", "FIN_CODE": "", "SUPPLIER_NAME": "", "SUPPLIER_ID": 
         2 = {dict: 3} {'environment_id': '9', 'environment_address': 'http://192.168.16.51:30911/', 'environment_name': '广州政采贷-webservice'}
         3 = {int} 202104141454892
         4 = {int} 1101
         5 = {str} '7'
         __len__ = {int} 6"""
        print("lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllll")
        interface_pici = args[3]  # 批次号
        execute = args[4]  # 执行条件
        progect_id = args[5]  # 新增2

        # 1.已知接口id,获取此接口下的测试案例（接口id + 执行条件类型）
        if execute == "2":# 常规测试2
            execute_new = "0"
            testcases = Interfaces_Case.getInterfacesCases(self.interfaces_id, execute_new)

        elif execute =='1101' :
            print("走流程测试=")
            interface_id=args[0]
            print(interface_id)   #341
            # testcases = Interfaces_Case.getInterfacesCasesFlow(self.interfaces_id)
            # print(testcases)  #[{'id': 114}]
            # print(type(testcases))

            dic_api_case=args[6]
            print(dic_api_case)#  {341: 114, 342: 111}
            print(type(dic_api_case))#<class 'dict'>
            j = json.dumps(dic_api_case)
            # key_value = jsonpath.jsonpath(j, '$..{key_name}'.format(key_name=interface_id))
            #
            #
            # caseID1111=self.get_json_value_by_key(eval(j), interface_id)
            print(int(dic_api_case[interface_id]))

            testcases=[{'id':int(dic_api_case[interface_id])}]
            print(testcases)
            print(type(testcases))



            print("前端传的case值为")

        else:#非常规
            execute_new = execute
            testcases = Interfaces_Case.getInterfacesCases(self.interfaces_id, execute_new)
            print(testcases)
            print("测试案例信息")

        if len(testcases) == 0:
            global teascase_fail
            teascase_fail += 1
            interface_fail_list.append(self.interfaces_id)

            #     测试案例维度添加执行记录

            interface_case_name = "None"
            check_key_lists = "None"
            check_condition_lists = "None"
            check_value_lists = "None"
            out_value_lists = "None(失败原因：执行的接口没有维护可执行的测试案例)"
            interface_res = "失败"
            action_condition = "None"
            param_in = "None"
            param_out = "失败原因：执行的接口没有维护可执行的测试案例"
            interface_name = Interfaces.getInterfacesName(self.interfaces_id)
            interfacesId = Lyzd_Interface.objects.get(id=self.interfaces_id)
            InterfaceCase_Action.addInterfaceCaseAction2(interface_pici, interfacesId, interface_name,
                                                         interface_case_name, check_key_lists, check_condition_lists,
                                                         check_value_lists, out_value_lists, interface_res)

            # 用例详情维度添加执行记录
            interfacecase_action_id = InterfaceCase_Action.getInterfaceCaseActionID(interface_pici, interface_name,
                                                                                    interface_case_name)
            interfacecase_action_id = list(interfacecase_action_id)[0]['id']

            Interface_Action_Detail.addInterfaceActionDetail(interfacecase_action_id, interface_case_name,
                                                             check_key_lists, check_condition_lists, check_value_lists,
                                                             out_value_lists,
                                                             action_condition,
                                                             param_in, param_out, interface_res)


        else:
            print("222222")
            for testcases_id in testcases:
                print(testcases)
                testcase_id = testcases_id['id']

                # 2.取测试案例信息{测试案例的全部信息
                test_case_datas = data_interface_cases_view(testcase_id, self.test_interfaces_datas, self.interfaces_id)
                print(test_case_datas)
                print("3333333")

                # 3.整合信息（环境+接口+案例）
                self.test_case_toll_datas = data_view(test_case_datas, self.test_interfaces_datas,
                                                      self.environment_data)
                print(self.test_case_toll_datas)
                print("4444444")

                # 4.取值
                self.testcasedata_datas = testcasedata_view(self.test_case_toll_datas)
                print(self.testcasedata_datas)
                print("5555555")

                # 5.案例执行；

                http_result = self.httpapi_views(self.testcasedata_datas, progect_id)  # 新增项目编号3

                if http_result == None:  # 表示没有返回值

                    param_in = self.testcasedata_datas['param_testcase_data']
                    param_out = "None(原因：接口信息或环境选择错误)"  # http_result
                    http_results1 = self.testcasedata_datas['assert_response']
                    action_condition = self.testcasedata_datas['action_condition']
                    test_case_result = '失败'

                    http_results = []
                    for key, item in http_results1.items():
                        dict1 = {}
                        http_resultli = []
                        dict1[key] = item
                        http_resultli.append(dict1)
                        http_resultli.append("None")
                        http_resultli.append("失败")
                        http_results.append(http_resultli)


                else:
                    print("用例详情统计")
                    param_in = test_case_datas['Querytestcases']['param_testcase_data']
                    print(param_in)
                    http_results = http_result[0]
                    print(http_results)
                    action_condition = test_case_datas['Querytestcases']['action_condition']
                    print(action_condition)
                    test_case_result = http_result[1]
                    print(test_case_result)


                    if args[1][0]['interface_data']['testcases_apihttptype'] == 'WebService':
                        param_out = self.responseJson_all
                    else:
                        print(self.responseJson)
                        param_out = self.responseJson

                # 6-2 测试案例统计:接口id,测试用例id,全部入参，全部的出参，断言结合，执行条件（且/或），用例执行结果，执行批次
                statistics_testcase_result = statistics_interface_action_detail(self.interfaces_id,
                                                                                testcase_id,
                                                                                param_in,
                                                                                param_out,
                                                                                http_results,
                                                                                action_condition,
                                                                                test_case_result,
                                                                                interface_pici)
                # print(statistics_testcase_result)

    def httpapi_views(self, *args, **kwargs):
        print("*args")
        print(*args)
        progect_id = args[1]
        print("项目标号为：%s" % progect_id)
        print(self.testcasedata_datas)

        try:
            # 1.根据接口认证判断
            if self.testcasedata_datas['interfaces_authentication'] == "0":

                # 1.调接口
                ret = http(method=self.testcasedata_datas['request_way'], url=self.testcasedata_datas['url'],
                           params=self.testcasedata_datas['param_testcase_data'],
                           headers=self.testcasedata_datas['header'])
                self.responseJson = ret[0]
                print(self.responseJson)


            elif self.testcasedata_datas[
                'interfaces_authentication'] == "1":  # 有认证 request_way param_testcase_data header
                testcases_apihttptype = args[0]['testcases_apihttptype']
                print("类型：%s" % testcases_apihttptype)

                if testcases_apihttptype == 'WebService':

                    # 取出请求头 + 请求体中header
                    headers = {'Content-Type': 'application/json'}

                    sourceBody = {}

                    # 去除Content-Type,作为加密body中的第一个参数
                    # 解包取出Content-Type，作为调真正接口的请求头
                    Content_Type_header = args[0]['header']
                    key, value = Content_Type_header.popitem()  # 去除Content-Type
                    header2 = dict()
                    header2[key] = value  # 真正接口的请求头{'key': 'application/xml'}

                    # reqHead 转xml
                    webserviceHead = json.dumps(Content_Type_header)
                    sourceHead2 = {}
                    sourceHead2['reqHeadDemo'] = eval(webserviceHead)
                    reqHead = json_to_xml(sourceHead2)

                    sourceBody['reqHead'] = reqHead  # 放入body字典中
                    print("放字典中:%s" % sourceBody)

                    testcases_isList = args[0]['testcases_isList']  # Y
                    if testcases_isList == 'Y':
                        print("=============================YYYYY")

                        testcases_listPadding = args[0]['testcases_listPadding']

                        if testcases_listPadding != '':
                            # 1.生成ListDate
                            ListData = {}
                            ListData['caseID'] = args[0]['testcases_id']  # 用例id
                            ListData['apiList'] = testcases_isList
                            ListData['apiListPadding'] = testcases_listPadding
                            print("SSSSSSSSSSSSSSSS")

                            print(ListData)

                            # 2-1.生成CaseDate
                            interfaceBody = Lyzd_Interface_Case_Param.objects.filter(
                                interface_cases=args[0]['testcases_id'])
                            serialize = Sys_CaseParamSerializer(interfaceBody, many=True)
                            print("SSSSSSS111111")

                            # 2-2np
                            keys1 = [str(x) for x in np.arange(len(serialize.data))]
                            list_json = dict(zip(keys1, serialize.data))
                            print("SSSSSSS2222222")

                            # 2-3body先转xml,再拼接
                            reqbody = xmlDataBuild(list_json, ListData)
                            print("+++++++++++++++")
                            print("+++++++++++++++")
                            print("+++++++++++++++")
                            print("+++++++++++++++")
                            print(reqbody)

                            # 3.开始拼接Body
                            sourceBody['reqBody'] = reqbody




                        else:
                            print("Y时，testcases_listPadding必须是非空，异常处理,后续补充")
                            pass
                    else:

                        print("是N")
                        print("=============================NNNNNN ")
                        bodyData = args[0]['param_testcase_data']
                        print("$$$$$$$$$$$$$$$$$$$$$$$$")
                        print(type(bodyData))
                        """
                        遍历key，value，查看value是否有list[],查询出并且替换

                        """

                        print(bodyData)
                        list_type = []
                        for value in bodyData.values():
                            print(value)
                            """list型json   [{"AA":"BB"}]
                            所以为防止参数值包含json形式的字符，所以分别对[{}]: 均存在则进行处理

                            """
                            if "[" in str(value) and "{" in str(value) and "}" in str(value) and "]" in str(
                                    value) and ":" in str(value):
                                print("yes")
                                print([list(bodyData.values()).index(value)])
                                print(list(bodyData.keys())[list(bodyData.values()).index(value)])
                                list_ = list(bodyData.keys())[list(bodyData.values()).index(value)]  # list类型的key
                                list_type.append(list_)

                            else:
                                print("no")
                        print(list_type)
                        print(list_type.__len__())
                        if list_type.__len__() > 1:
                            print("此处有问题，同为list如何处理，需要核对接口文档")
                        elif list_type.__len__() == 0:
                            print("无需处理")

                        else:
                            """构建替换参数"""
                            for i in iter(list_type):
                                print(i)
                                print("[{'" + i + "':" + str(bodyData[i]) + "}]")
                                # del Content_Type_header['Content-Type']
                                print(123456)
                                print(bodyData)

                                print(type(bodyData))
                                # bodyData['LIST'] =  [{'" + i + "':" + str(bodyData[i]) + "}]

                                print(1)
                                print(bodyData)
                                print(2)
                                print(str(bodyData[i]))
                                bodyData["LIST"] = list([{i: list(bodyData[i])}])
                                print(3)
                                print(bodyData)
                                del bodyData[i]
                                print(bodyData)
                                # print(json.dumps(bodyData))
                                # replace= "[{'" + i + "':" + str(bodyData[i]) + "}]"
                                # print(replace)

                                print("######################")
                        print(bodyData)
                        print("######################")

                        # print(args[0]['param_testcase_data'])
                        webserviceBody = json.dumps(bodyData)
                        print(webserviceBody)
                        sourceBody2 = {}
                        sourceBody2['reqBodyDemo'] = eval(webserviceBody)
                        reqBody = json_to_xml(sourceBody2)
                        print("=====================")
                        print(type(reqBody))
                        print(reqBody)
                        print("=======替换==============")
                        reqBody = reqBody.replace('<?xmlversion="1.0"encoding="utf-8"?><reqBodyDemo>', '')
                        reqBody = reqBody.replace('</reqBodyDemo>', '')

                        print(reqBody)
                        # 3.开始拼接Body
                        sourceBody['reqBody'] = reqBody
                        print("=====================")
                        # """webservice 无list时，包含参数内带list，整体body非list"""
                        # interfaceBody = Lyzd_Interface_Case_Param.objects.filter(
                        #     interface_cases=args[0]['testcases_id'])
                        # print(interfaceBody)
                        # serialize = Sys_CaseParamSerializer(interfaceBody, many=True)
                        # print(serialize.data)
                        # print(type(serialize.data))
                        # print("000000")

                    self.responseJson_all = []  # WebService 时出参拼接四部分：1.加密前信息+ 2. 加密后信息 3.执行后信息 4.解密后信息
                    d1 = dict(调加密接口前数据=sourceBody)
                    self.responseJson_all.append(d1)

                    # 4.调加密接口
                    ret = http(method=self.testcasedata_datas['request_way'],
                               url=self.testcasedata_datas['interfaces_encryption_url'],
                               params=sourceBody,
                               headers=headers)
                    print("响应值1")
                    self.responseJson = ret[0]
                    print(self.responseJson)

                    # 调加密后存储
                    d2 = dict(调加密后存储数据=self.responseJson)
                    self.responseJson_all.append(d2)

                    # 5.replaceBody 替换
                    result = replaceBody(self.responseJson)
                    data = replacePayload(result)
                    print(data)

                    # 6.调真正的接口
                    ret = http(method=self.testcasedata_datas['request_way'],
                               url=args[0]['url'],
                               params=data,
                               headers=header2)
                    print("响应值2")
                    self.responseJson = ret[0]
                    print(self.responseJson)

                    # 执行后存储
                    d3 = dict(执行后存储数据=self.responseJson)
                    self.responseJson_all.append(d3)

                    # 7.调解密接口
                    param = replaceXmlPretty(self.responseJson)
                    ret = http(method=self.testcasedata_datas['request_way'],
                               url=args[0]['interfaces_decrypt_url'],
                               params=param,
                               headers=headers)

                    print("响应值3")
                    self.responseJson = ret[0]
                    print(self.responseJson)

                    # 解密后存储
                    d4 = dict(解密后存储数据=self.responseJson)
                    self.responseJson_all.append(d4)
                    print(self.responseJson_all)





                else:
                    print("走原来")

                    #     1-1调加密接口
                    encryption_ret = Encryption(self.testcasedata_datas['interfaces_encryption_url'],
                                                self.testcasedata_datas['request_way'],
                                                self.testcasedata_datas['param_testcase_data'],
                                                self.testcasedata_datas['header'])
                    print("加密返回值:%s" % encryption_ret)

                    #  1-2重新拼接用例data内容
                    if progect_id == "6" or progect_id == "8":  # 广州政采代项目编号为6，将参数"20000303", "20000300"替换
                        encryption_ret['merchantNo'] = '20000300'
                        print("替换后的值:%s" % encryption_ret)

                        self.testcasedata_datas['param_testcase_data'] = encryption_ret
                        print("重新拼接后的案例-6：%s" % self.testcasedata_datas)
                        ret = http(method=self.testcasedata_datas['request_way'], url=self.testcasedata_datas['url'],
                                   params=self.testcasedata_datas['param_testcase_data'],
                                   headers=self.testcasedata_datas['header'])
                        self.responseJson = ret[0]
                        print("self.responseJson:%s" % self.responseJson)
                        print("广州实际返回值！！！！！！！！！！")


                    else:  # 原有的解密及解密
                        self.testcasedata_datas['param_testcase_data'] = encryption_ret
                        print("重新拼接后的案例(原来)：%s" % self.testcasedata_datas)
                        ret = http(method=self.testcasedata_datas['request_way'], url=self.testcasedata_datas['url'],
                                   params=self.testcasedata_datas['param_testcase_data'],
                                   headers=self.testcasedata_datas['header'])
                        print("ret:%s" % ret[0])

                        # 1-3  解密url,data,method,header
                        self.responseJson = Decrypt(self.testcasedata_datas['interfaces_decrypt_url'],
                                                    self.testcasedata_datas['request_way'], ret[0],
                                                    self.testcasedata_datas['header'])
                        print("decrypt_ret:%s" % self.responseJson)

            # 2.断言
            print("断言开始")
            print(self.testcasedata_datas)
            print(self.testcasedata_datas['assert_response'])
            print(self.responseJson)
            assert_response_list_all = carry_assert(self.testcasedata_datas['assert_response'], self.responseJson)
            print("接收实际的返回结果:%s" % assert_response_list_all)

            # 3.根据断言结果统计单个案例执行结果
            test_case_result = test_case_judge(self.testcasedata_datas['assert_response'],
                                               self.testcasedata_datas['action_condition'])
            print('此条案例id=%s的执行结果为%s' % (self.testcasedata_datas['testcases_id'], test_case_result))

            #   4.根据接口统计执行结果
            if test_case_result == 'success':
                global teascase_pass, regular_check_seccess_data
                teascase_pass += 1
                print('此接口id=%s成功的测试案例数量为：%s' % (self.testcasedata_datas['interfaces_id'], teascase_pass))
                interface_succcess_list.append(self.testcasedata_datas['interfaces_id'])
                print("接口执行成功的列表：%s" % interface_succcess_list)

                # 接口测试案例执行成功得信息进行存储；为了常规校验传参做准备；[id,self.test_case_toll_datas]
                # 因为常规校验针对得是一个接口对应一个疏通测试；如果一个接口对应多个疏通测试时，不支持
                regular_check_seccess_data.append(self.test_case_toll_datas)
                return assert_response_list_all, test_case_result

            else:
                global teascase_fail
                teascase_fail += 1
                # print('此接口id=%s失败的测试案例数量为：%s' % (self.testcasedata_datas['interfaces_id'], teascase_fail))
                interface_fail_list.append(self.testcasedata_datas['interfaces_id'])
                # print("接口执行失败的列表：%s" % interface_fail_list)
                return assert_response_list_all, test_case_result



        except Exception as e:
            # 接口api错误或环境配置错误
            teascase_fail += 1
            # print('此接口id=%s失败的测试案例数量为：%s' % (self.testcasedata_datas['interfaces_id'], teascase_fail))
            interface_fail_list.append(self.testcasedata_datas['interfaces_id'])
            # print("接口执行失败的列表：%s" % interface_fail_list)

    def get_json_value_by_key(self, in_json, target_key, results=[]):
        """
        根据key值读取对应的value值
        :param in_json:传入的json
        :param target_key: 目标key值
        :param results:
        :return:
        """
        if isinstance(in_json, dict):  # 如果输入数据的格式为dict
            for key in in_json.keys():  # 循环获取key
                data = in_json[key]
                self.get_json_value_by_key(data, target_key, results=results)  # 回归当前key对于的value
                if key == target_key:  # 如果当前key与目标key相同就将当前key的value添加到输出列表
                    results.append(data)
        elif isinstance(in_json, list) or isinstance(in_json, tuple):  # 如果输入数据格式为list或者tuple
            for data in in_json:  # 循环当前列表
                self.get_json_value_by_key(data, target_key, results=results)  # 回归列表的当前的元素
        return results